<?php

namespace App\Console\Commands;

use App\Http\Controllers\HelperController;
use App\Imports\Gas\GasImport;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;

class checkSkImportData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 读取文件列表
        $gasPath = public_path('gas\\');
        $files = File::allFiles($gasPath);

        $fileCount = count($files);
        $chazhiCount = 0;
        $chazhiAmount = 0;
        $successCount = 0;
        $faileCount = 0;
        $importSuccessCount = 0;
        $totalCount = 0;
        $totalAmount = 0;
        foreach ($files as $k => $file) {
            $importData = $this->importGas($file->getRealPath());
            if ($importData) {
                $importSuccessCount++;
            }
            $count = str_replace(',', '', $importData['count']);
            $gasCount = str_replace(',', '', $importData['gasCount']);
            $amount = str_replace(',', '', $importData['amount']);
            $gasAmount = str_replace(',', '', $importData['gasAmount']);
            if (($count === $gasCount) && ($amount === $gasAmount)) {
                $totalCount += $count;
                $totalAmount += $amount;
                $successCount++;
                $this->info('- '.$file->getFilename());
                $this->info('- 记录值汇总：'.$importData['count'].' | '.$importData['amount']);
                $this->info('- 原始汇总：'.$importData['gasCount'].' | '.$importData['gasAmount']);
                $this->info(PHP_EOL);
            } else {
                $faileCount++;
                $this->error('- '.$file->getFilename());
                $this->error('- 记录值汇总：'.$importData['count'].' | '.$importData['amount']);
                $this->error('- 原始汇总：'.$importData['gasCount'].' | '.$importData['gasAmount']);
                $chazhiCount += ($importData['gasCount'] - $importData['count']);
                $chazhiAmount += $importData['gasAmount'] - $importData['amount'];
                $this->error('- 差值：'.($importData['gasCount'] - $importData['count']).' | '.($importData['gasAmount'] - $importData['amount']));
                $this->info(PHP_EOL);
            }
        }
        $this->info("- 导入成功：{$importSuccessCount}/{$fileCount}");

        $this->info("- 核验成功：{$successCount}");
        $this->info("- 核验失败：{$faileCount}");

        $this->info("- 气量合计：{$totalCount}");
        $this->info("- 金额合计：{$totalAmount}");
    }

    public function importGas($path)
    {
        $excelData = Excel::toArray(new GasImport, $path);
        $fullData = $excelData[0];

        // 删除前三行
        array_shift($fullData);
        array_shift($fullData);
        array_shift($fullData);

        // 最后一行数据
        $endData = end($fullData);
        // 删除最后一行
        array_pop($fullData);

        $data = [];
        $fields = [
            'date_time',
            'gun_num',
            'serial_num',
            'post_num',
            'gas_count',
            'gas_amt',
            'gas_unit_amt',
            'card_region_num',
            'card_operator_num',
            'user_card_num',
            'card_type',
            'car_type',
            'license_plate_num',
            'line',
            'consumption_patterns',
            'card_balance',
            'team',
            'employee_card_num',
            'is_paid',
            'cashier',
            'sign',
            'start_pressure',
            'end_pressure',
            'add_gas_long',
            'stop_all_gas',
            'offset',
            'density',
        ];
        // 整理数据，填充合并的单元格数据
        foreach ($fullData as $k => $row) {
            $item = [];
            foreach ($fields as $index => $field) {
                $item[$field] = $row[$index];
            }
            if ($item['license_plate_num']) {
                $item['license_plate_num'] = Str::of($item['license_plate_num'])->replace('陕G', '');
            }
            $item['date_time'] = HelperController::transformDateTime($item['date_time'], 'Y-m-d H:i:s');
            $item['created_at'] = date('Y-m-d H:i:s');
            $data[] = $item;
        }

        // 获取气量和金额合计
        $gasCount = $this->sumFiled($data, 'gas_count');
        $gasAmount = $this->sumFiled($data, 'gas_amt');

        $count = (float) str_replace('总气量：', '', $endData[5]);
        $amount = (float) str_replace('总金额：', '', $endData[8]);

        return [
            'count'     => number_format($count, 2),
            'amount'    => number_format($amount, 2),
            'gasCount'  => number_format($gasCount, 2),
            'gasAmount' => number_format($gasAmount, 2),
        ];
    }

    public function sumFiled($arr, $filed)
    {
        $sum = 0;
        foreach ($arr as $item) {
            $sum += $item[$filed];
        }

        return $sum;
    }
}
